﻿using System;
using System.IO;
using Microsoft.SqlServer.Server;
using Mono.Data.Sqlite;
using UnityEngine;
/*
 * “.db”文件一般是软件用于存放数据的一个文件，相当于数据库，每种软件都有它自己的存放格式，就是数据的排列方式；
 * 一些软件数据文件后缀名均为“db”；该文件可以用“sqlitespy”或“SqliteStudio”工具打开
 */
/// <summary>
/// sqlite连接基类
/// </summary>
public class SqlDbConnect
{
    protected SqliteConnection _sqliteConn;

    public SqliteConnection SqliteConn => _sqliteConn;
    public SqlDbConnect(string dbPath)
    {
        if (!File.Exists(dbPath))
        {
            CreateDbSqlite(dbPath);
        }

        ConnectDbSqlite(dbPath);
    }

    public static SqlDbConnect CreateSqlDbConn(string dbPath)
    {
        return new SqlDbConnect(dbPath);
    }
    /// <summary>
    /// 创建sqlite数据库文件
    /// </summary>
    /// <param name="dbPaht">文件具体路径</param>
    /// <returns></returns>
    public static bool CreateDbSqlite(string dbPaht)
    {
        try
        {
            //如果文件父级目录不存在  则创建父级目录
            string dirName=new FileInfo(dbPaht).Directory.FullName;
            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }

            if (File.Exists(dbPaht))
            {
                Debug.LogWarning("数据库文件已存在 "+dbPaht);
                return false;
            }
            else
            {
                SqliteConnection.CreateFile(dbPaht);
            }
            return true;
        }
        catch (Exception e)
        {
            Debug.LogError($"数据库创建异常：{e.Message}");
            return false;
        }
    }

    /// <summary>
    /// 连接sqlite数据库
    /// </summary>
    /// <param name="dbPath"></param>
    /// <returns></returns>
    private bool ConnectDbSqlite(string dbPath)
    {
        try
        {
            //SqliteConnectionStringBuilder  拼接字符 给文件路径加上Data Source=
            _sqliteConn = new SqliteConnection(new SqliteConnectionStringBuilder() {DataSource = dbPath}.ToString());
            _sqliteConn.Open();
            return true;
        }
        catch (Exception e)
        {
            Debug.LogError($"数据库连接异常：{e.Message}");
            return false;
        }
    }
    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose()
    {
        _sqliteConn.Dispose();
    }
}